<?php defined('SYSPATH') or die('No direct script access.');

class MyBankAccount_Controller extends OrgController {

    public $DISPLAY_SEMINAR_LIST_UUID = 'org/bankAccount/display/seminarList';
    public $DISPLAY_VISEMINAR_LIST_UUID = 'org/bankAccount/display/viSeminarList';


    public function __construct() {
        $this->formName = 'org/myBankAccount';
        $this->setDefaultListOrder('name');
        parent::__construct('bankAccount');
        $this->activeMenuItem = OrgMenu::$MY_BANK_ACCOUNTS;
    }
    
    public function all() {
        $this->initPagination('bank_account');
        
        $this->viewData['bankAccountList'] = $this->dao->queryAll($this->orderLimitAndOffset(
                'SELECT acc.* FROM bank_account acc WHERE acc.organization_id = :id'), 
                array('id' => $this->getAuthOrg('id'))
        );
        
        $this->renderSubview('/org/myBankAccount/myBankAccountList');
    }
    
    public function display() {
        $id = $this->input->get('id');

        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }
        
        $bankAccount = $this->dao->getById('bank_account', $id);
        if (! $bankAccount || ($this->getAuthOrg('id') != $bankAccount['organization_id'])) {
            $this->redirectToList('error.recordNotFound');
        }
        $bankAccount['organization'] = $this->dao->getById('organization', $bankAccount['organization_id']);
        $this->viewData['bankAccount'] = $bankAccount;

        $this->viewData['bankAccountIsUsed'] = $this->isUsed($id);

        if (! request::is_ajax()) {
            // Seminars
            $this->viewData['seminarList'] = $this->dao->queryAll(sql::orderBy($this->DISPLAY_SEMINAR_LIST_UUID,
                    'SELECT sem.*, l10n.name ' .
                    'FROM payment_acceptance pa ' .
                    'LEFT OUTER JOIN seminar sem ON sem.id = pa.seminar_id ' .
                    'LEFT OUTER JOIN seminar_l10n l10n ON l10n.seminar_id = sem.id AND l10n.language_code = :language_code ' .
                    'WHERE pa.bank_account_id = :bank_account_id ', 'begin_date'),
                    array(
                        'bank_account_id' => $id,
                        'language_code' => $this->getL10nLanguageCode()
                    ));

            // Weekend seminars
            $this->viewData['viSeminarList'] = $this->dao->queryAll(sql::orderBy($this->DISPLAY_VISEMINAR_LIST_UUID,
                    'SELECT se.* FROM vi_seminar se ' .
                    'WHERE se.bank_account_id = :id', 'begin_date'),
                    array('id' => $id));
        }
        
        $this->renderSubview('/org/myBankAccount/myBankAccountDisplay');
    }

    protected function isUsed($id) {
        $viSeminarCount = $this->dao->queryCount(
                'SELECT count(*) FROM vi_seminar WHERE bank_account_id = :id',
                array('id' => $id));
        $paCount = $this->dao->queryCount(
                'SELECT count(*) FROM payment_acceptance WHERE bank_account_id = :id',
                array('id' => $id));
        return $viSeminarCount + $paCount > 0;
    }

    public function edit() {
        $id = $this->input->get('id');
        $bankAccount = array();

        if ($id) {
            $bankAccount = $this->dao->getById('bank_account', $id);
            if (! $bankAccount || ($this->getAuthOrg('id') != $bankAccount['organization_id'])) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // Set default values for a new record here
            $bankAccount['enabled'] = sql::$TRUE;
        }
        
        $this->loadFormData();
        
        $this->viewData['bankAccount'] = $bankAccount;
        $this->renderSubview('/org/myBankAccount/myBankAccountEdit');
    }
    
    protected function loadFormData() {
        $this->viewData['bankNameAcValues'] = $this->dao->queryFirstValues(
                'SELECT DISTINCT bank_name FROM bank_account ' .
                'WHERE organization_id = :id ORDER BY bank_name ASC',
                array('id' => $this->getAuthOrg('id')));
    }
    
    public function save() {
        $bankAccount = $this->postToDbValues();
        $id = $bankAccount['id'];
        $this->viewData['bankAccount'] = $bankAccount;
        
        if ($this->isUsed($id)) {
            $this->redirectToList('bankAccount.error-cannotBeEdited');
        }

        // Basic validation
        $validator = new EntityValidator($bankAccount, 'bankAccount', $this->msg);
        $validator->required('name');
        $validator->required('bank_name');
        $validator->required('number');
        $validator->required('bank_number');
        
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->renderSubview('/org/myBankAccount/myBankAccountEdit');
            return;
        }

        // Database validation
        if ($this->dao->alreadyExists('bank_account', 'name', $bankAccount)) {
            $this->loadFormData();
            $this->msg->error('bankAccount.error-alreadyExists', $bankAccount['name']);
            $this->renderSubview('/org/myBankAccount/myBankAccountEdit');
            return;
        }

        // Insert/update
        unset($bankAccount['organization']);
        $bankAccount['organization_id'] = $this->getAuthOrg('id');
        if ($id != null) {
            $editedRecord = $this->dao->getById('bank_account', $id);
            if (! $editedRecord || ($this->getAuthOrg('id') != $editedRecord['organization_id'])) {
                $this->redirectToList('error.recordNotFound', $bankAccount['name']);
            }

            $this->dao->update('bank_account', $bankAccount);
            $this->msg->info('bankAccount.editSuccess', $bankAccount['name']);
        }
        else {
            $bankAccount['enabled'] = sql::$TRUE;
            $id = $this->dao->insert('bank_account', $bankAccount);
            $this->msg->info('bankAccount.createSuccess', $bankAccount['name']);
        }
        
        $this->redirect('/org/myBankAccount/all');
    }
    
    public function delete() {
        $id = $this->input->get('id');
        
        // Basic validation
        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }

        $bankAccount = $this->dao->getById('bank_account', $id);
        if (! $bankAccount || ($this->getAuthOrg('id') != $bankAccount['organization_id'])) {
            $this->redirectToList('error.recordNotFound');
        }
        
        $this->dao->delete('bank_account', $id);

        $this->msg->info('bankAccount.deleteSuccess', $bankAccount['name']);
        $this->redirectToList('/org/myBankAccount/all');
    }

    public function disable() {
        return $this->enableAccount(FALSE);
    }

    public function enable() {
        return $this->enableAccount(TRUE);
    }

    public function enableAccount($enable) {
        $id = $this->input->get('id');

        // Basic validation
        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }

        $bankAccount = $this->dao->getById('bank_account', $id);
        if (! $bankAccount || ($this->getAuthOrg('id') != $bankAccount['organization_id'])) {
            $this->redirectToList('error.recordNotFound');
        }
        $bankAccount['enabled'] = ($enable ? sql::$TRUE : sql::$FALSE);

        $this->dao->update('bank_account', $bankAccount);

        $this->msg->info('bankAccount.' . ($enable ? 'enable' : 'disable') . 'Success', $bankAccount['name']);
        $this->redirect('org/myBankAccount/display?id=' . $id);
    }
    
    public function displaySeminar() {
        $id = $this->input->get('id');

        // Basic validation
        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }

        $seminar = $this->dao->fetchSeminar($id, $this->getL10nLanguageCode());
        $this->viewData['seminar'] = $seminar;
        $this->viewData['displayInMainWindowIcon'] = FALSE;
        $this->renderSubview('org/seminar/seminarDisplay');
    }
}
